package session

import (
	"errors"
	"net/http"

	"chainmaker.org/chainmaker/smarteditor/common"
)

func GetUidFromSession(request *http.Request) (string, error) {
	if IsNewSession(request) {
		return "", errors.New(common.Forbidden)
	}

	uid := getUid(request)
	if uid == "" {
		return "", errors.New(common.Forbidden)
	}
	return uid, nil
}

func IsNewSession(request *http.Request) bool {
	httpSession, _ := HTTPSession.Get(request, CookieName)
	if httpSession.IsNew {
		return true
	}
	return false
}

//get uid from session
func getUid(request *http.Request) string {
	httpSession, _ := HTTPSession.Get(request, CookieName)
	s, ok := httpSession.Values[common.UidName].(string)
	if !ok {
		log.Warnf("get uid uid type is not string.")
		return ""
	}
	return s
}
